<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('店铺购买页面')"/>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>图书名称：</label>
                            <input type="text" name="fruitName"/>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                    class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                    class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
        <!-- 购物车面板 - 固定定位在底部 -->
        <div class="col-sm-12" style="padding: 15px;">
            <div class="panel panel-info">
                <div class="panel-heading">购物车</div>
                <div class="panel-body">
                    <p id="cart-items">当前购物车为空</p>
                    <p id="total-value">总价值：0 元</p>
                    <!-- 加入结算按钮 -->
                    <button id="settlementButton" class="btn btn-primary">结算</button>
                </div>
            </div>
        </div>
    </div>
</div>

</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">

    var prefixDessert = ctx + "system/novel";
    var createOrderUrl = ctx + "system/shopping/create";
    var cartMap = {};

    function updateCartItems(cartData) {
        console.log("cartData:{}", JSON.stringify(cartData))
        console.log("cartMap:{}", JSON.stringify(cartMap))
        var itemsText = '';
        var totalValue = 0;
        for (var item of cartData) {
            if (item.type === 'add') {
                if (cartMap[item.id + '_' + item.proType]) {
                    console.log("add...")
                    cartMap[item.id + '_' + item.proType].quantity++;
                } else {
                    cartMap[item.id + '_' + item.proType] = {
                        name: item.name,
                        price: item.price,
                        quantity: 1,
                        proType: item.proType
                    };
                }
            } else if (item.type === 'remove') {
                console.log("remove...")
                if (cartMap[item.id + '_' + item.proType] && cartMap[item.id + '_' + item.proType].quantity > 0) {
                    cartMap[item.id + '_' + item.proType].quantity--;
                    if (cartMap[item.id + '_' + item.proType].quantity === 0) {
                        delete cartMap[item.id + '_' + item.proType];
                    }
                }
            }
        }

        for (var itemName in cartMap) {
            console.log("itemName :", itemName);
            var item = cartMap[itemName];
            itemsText += item.name + '*' + item.quantity + ', ';
            totalValue += item.price * item.quantity;
        }

        itemsText = itemsText.slice(0, -2); // 去除最后多余的逗号和空格

        $('#cart-items').text(itemsText);
        $('#total-value').text('总价值：' + totalValue + ' 元');
    }

    // 为结算按钮添加点击事件
    $('#settlementButton').click(function () {
        var cartData = [];
        for (var itemName in cartMap) {
            var item = cartMap[itemName];
            cartData.push({
                id: itemName,
                proType: item.proType,
                quantity: item.quantity
            });
        }
        var totalValueText = $('#total-value').text();
        var totalValue = parseFloat(totalValueText.match(/\d+\.\d+|\d+/)[0]);
        $.ajax({
            type: 'POST',
            url: createOrderUrl,
            dataType: 'json',
            data: JSON.stringify({
                shoppingDTOList: cartData
            }),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                console.log(JSON.stringify({
                    shoppingDTOList: cartData
                }))
                // 弹窗提示
                alert('订单创建成功');
            },
            error: function (error) {
                console.log(error);
            }
        });
    });


    $(function () {
        var options = {
            method: 'POST',
            url: prefixDessert + "/list",
            removeUrl: prefixDessert + "/remove",
            modalName: "图书",
            pagination: true,            // 必须显式开启
            pageSize: 10,                // 默认分页大小
            pageList: [10, 25, 50],      // 可选分页大小
            showPageGo: true,            // 显示快速跳转
            showRefresh: true,           // 显示刷新按钮
            sidePagination: "server",
            columns: [{
                checkbox: true
            },
                {
                    field: 'index',
                    title: '序号',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    field: 'novelId',
                    title: '主键',
                    visible: false
                },
                {
                    field: 'authorName',
                    title: '作者'
                },
                {
                    field: 'categoryName',
                    title: '小说分类'
                },
                {
                    field: 'title',
                    title: '小说标题'
                },
                {
                    field: 'description',
                    title: '小说描述'
                },
                {
                    field: 'price',
                    title: '价格'
                },
                {
                    field: 'stock',
                    title: '库存'
                },
                {
                    field: 'createTime',
                    title: '上架时间'
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.addToCart(\'' + row.novelId + '\', \'' + row.title + '\', \'' + row.price + '\',\'' + '0' + '\')">添加到购物车</a> ');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.novelId + '\', \'' + '0' + '\')" ' + (!cartMap[row.title] ? 'disabled="disabled"' : '') + '>移除</a>');
                        return actions.join('');
                    }
                }]
        };
        $('#bootstrap-table').bootstrapTable(options);
    });

    // 添加到购物车的操作函数
    $.operate.addToCart = function (id, name, price, proType) {

        updateCartItems([{id: id, name: name, price: price, type: "add", proType: proType}]);
    };

    // 移除的操作函数
    $.operate.remove = function (id, proType) {
        console.log("移除购物车 :", id);
        // 这里实现移除的逻辑
        updateCartItems([{id: id, type: "remove", proType: proType}]);
    };
</script>
</body>
</html>